<?php

namespace Icsoc\EvaluateBundle\Controller;

use Icsoc\ReportBundle\Controller\ReportController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Icsoc\ExportLib\Col;

/**
 * Class DefaultController
 * @package Icsoc\EvaluateBundle\Controller
 */
class DefaultController extends ReportController
{
    /** @var array 播放次数 */
    private $retryTimes = array(1=>1, 2=>2, 3=>3);

    /** @var array 有效按键 */
    private $validkeys = array(
        '1' => 'key 1',
        '2' => 'key 2',
        '3' => 'key 3',
        '4' => 'key 4',
        '5' => 'key 5',
        '6' => 'key 6',
        '7' => 'key 7',
        '8' => 'key 8',
        '9' => 'key 9',
        '0' => 'key 0',
    );

    /** @var array 呼叫类型 */
    private $callType = array('1'=>'呼出', '2'=>'呼入');

    /** @var array 评价结果 */
    private $evaluates = array(
        '1'=>'评价成功',
        '-3' => '未评价挂机',
        '-4'=>'坐席挂机',
        '-1'=>'客户挂机'
    );

    private $_options = array(
        1=>'按键1',
        2=>'按键2',
        3=>'按键3',
        4=>'按键4',
        5=>'按键5',
        6=>'按键6',
        7=>'按键7',
        8=>'按键8',
        9=>'按键9'
    );

    /**
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function indexAction()
    {
//        $vccId = $this->getVccId();
//        $sounds = $this->get('icsoc_data.model.sound')->getSoundsArray($vccId);
//        $evaluateConfig = $this->container->get('icsoc_data.model.evaluate')
//            ->getEvaluateConfig(
//                array(
//                    'vccId'=> $vccId
//                )
//            );
//
//        $radioChecked = '';
//        $customSelect = array();
//        if (!empty($evaluateConfig)) {
//            $evaluateConfig = json_decode($evaluateConfig, true);
//            $customSelect = $evaluateConfig;
//            foreach ($evaluateConfig as $evaluate => $config) {
//                if (isset($config['evaluate_type'])) {
//                    if ($config['evaluate_type'] == 1) {
//                        $radioChecked = '3';
//                    } else if ($config['evaluate_type'] == 2) {
//                        $radioChecked = '2';
//                    } else if ($config['evaluate_type'] == 3) {
//                        $radioChecked = '4';
//                    }
//                } else {
//                    $radioChecked = '1';
//                }
//            }
//        }
//        $options = $this->_options;
        $vccId = $this->getVccId();
        $isOrigin = $this->container->get('icsoc_data.model.evaluate')->getEvaluateVerByVccId($vccId);
        if ($isOrigin == 1) {
            return $this->render('IcsocEvaluateBundle:Default:originIndex.html.twig');
        }
        $sounds = $this->get('icsoc_data.model.sound')->getEvaluateSounds($vccId);
        $evaConfig = $this->get('doctrine.dbal.default_connection')->fetchColumn(
            "SELECT evaluate_config FROM cc_evaluates_config WHERE vcc_id = ? LIMIT 1",
            array($vccId)
        );
        if (empty($evaConfig)) {
            $evaType = 1; //默认为1;
            $evaConfig = json_encode($evaConfig);
        } else {
            $config = json_decode($evaConfig, true);
            $evaType = isset($config['1']['evaluate_type']) ? $config['1']['evaluate_type'] : 4;
        }
        return $this->render(
            'IcsocEvaluateBundle:Default:index2.html.twig',
            array(
                'sounds' => $sounds,
                'evaConfig' => $evaConfig,
                'vccId' => $vccId,
                'evaType' => $evaType,
            )
        );
    }

    /**
     * the evaluate configuration list data
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function listAction(Request $request)
    {
        $page = $request->get('page', 1);
        $rows = $request->get('rows', 10);
        $sord = $request->get('sord', 'asc');
        $sidx = $request->get('sidx', 'id');
        $fliter = $request->get('fliter', '');

        $info = array(
            'pagination'=>array('rows'=>$rows, 'page'=>$page),
            'sort'=>array('order'=>$sord, 'field'=>$sidx),
            'filter'=> !empty($fliter) ? json_decode($fliter, true) : array(),
        );

        $vccCode = $this->getUser()->getVccCode();
        $list = $this->container->get('icsoc_data.model.evaluate')
            ->evaluateList(array('vcc_code'=>$vccCode, 'info'=>json_encode($info)));

        $data['rows'] = (isset($list['data']) && !empty($list['data'])) ? $list['data'] : array();
        $data['page'] = $page;
        $data['total'] = isset($list['totalPage']) ? $list['totalPage'] : 0;
        $data['records'] = isset($list['total']) ? $list['total'] : 0;

        return new JsonResponse($data);
    }

    /**
     * Add the evaluate configuration
     *
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function addAction(Request $request)
    {
        if ($request->getMethod() == 'POST') {
            $params['vcc_code'] = $this->getUser()->getVccCode();
            $params['name'] = $request->get('evaluate_name', '');
            $params['sound'] = $request->get('evaluate_sound', '');
            $params['play_order'] = $request->get('evaluate_play_order', '');
            $params['retry_times'] = $request->get('evaluate_retry_times', '');
            $params['valid_keys'] = $request->get('evaluate_valid_keys', array());
            $params['valid_keys'] = implode(',', $params['valid_keys']);

            $msg = $this->get('icsoc_data.model.evaluate')->add($params);
            if (isset($msg['code']) && $msg['code'] == '200') {
                $data = array(
                    'data'=>array(
                        'msg_detail'=>$this->trans('Evaluate Setting Success'),
                        'type' => 'success',
                        'link' => array(
                            array('text'=>$this->trans('Continue Add Evaluate'), 'href'=>$this->generateUrl('icsoc_evaluate_add')),
                            array('text'=>$this->trans('Evaluate List'), 'href'=>$this->generateUrl('icsoc_evaluate_index')),
                        ),
                    ),
                );
            } else {
                $data = array('data'=>array('msg_detail'=>$msg['message'], 'type'=>'danger'));
            }

            return $this->redirect($this->generateUrl('icsoc_ui_message', $data));
        }

        $vccId = $this->getUser()->getVccId();
        $sounds = $this->get('icsoc_data.model.sound')->getSoundsArray($vccId);

        return $this->render(
            'IcsocEvaluateBundle:Default:info.html.twig',
            array(
                'sounds' => $sounds,
                'valid_keys' => $this->validkeys,
                'retry_times' => $this->retryTimes,
            )
        );
    }

    /**
     * Edit the evaluate configuration
     *
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function editAction(Request $request)
    {
        $evaluateConfig = $request->get('evaluateConfig', '');
        $vccCode = $this->getVccCode();
        $message = $this->container->get('icsoc_data.model.evaluate')->update(
            array(
                'evaluateConfig' => $evaluateConfig,
                'vccCode' => $vccCode,
            )
        );

        return new JsonResponse($message);
    }

    public function editForOriginAction(Request $request)
    {
        $id = $request->get('id', '');

        if ($request->getMethod() == 'POST') {
            $params['vccCode'] = $this->getUser()->getVccCode();
            $params['id'] = $id;
            $params['name'] = $request->get('evaluate_name', '');
            $params['sound'] = $request->get('evaluate_sound', '');
            $params['play_order'] = $request->get('evaluate_play_order', '');
            $params['retry_times'] = $request->get('evaluate_retry_times', '');
            $params['valid_keys'] = $request->get('evaluate_valid_keys', array());
            $params['valid_keys'] = implode(',', $params['valid_keys']);

            $msg = $this->get('icsoc_data.model.evaluate')->updateForOriginEvaluate($params);
            if (isset($msg['code']) && $msg['code'] == '200') {
                $data = array(
                    'data'=>array(
                        'msg_detail'=>$this->trans('Evaluate Setting Success'),
                        'type' => 'success',
                        'link' => array(
                            array(
                                'text'=>$this->trans('Evaluate List'),
                                'href'=>$this->generateUrl('icsoc_evaluate_index'),
                            ),
                            array(
                                'text'=>$this->trans('Continue Edit Evaluate'),
                                'href'=>$this->generateUrl('icsoc_evaluate_editOrigin', array('id'=>$id)),
                            ),
                        ),
                    ),
                );
            } else {
                $data = array('data'=>array('msg_detail'=>$msg['message'], 'type'=>'danger'));
            }

            return $this->redirect($this->generateUrl('icsoc_ui_message', $data));
        }

        $evaluateInfo = $this->get('icsoc_data.model.evaluate')->getEvaluateInfo($this->getUser()->getVccCode(), $id);
        $data = isset($evaluateInfo['data']) ? $evaluateInfo['data'] : array();

        $vccId = $this->getUser()->getVccId();
        $sounds = $this->get('icsoc_data.model.sound')->getSoundsArray($vccId);

        return $this->render(
            'IcsocEvaluateBundle:Default:info.html.twig',
            array(
                'evaluateInfo' => $data,
                'sounds' => $sounds,
                'valid_keys' => $this->validkeys,
                'retry_times' => $this->retryTimes,
            )
        );
    }

    /**
     * Delete the evaluate configuration
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function deleteAction(Request $request)
    {
        $ids = $request->get('id', '');
        $result = $this->get('icsoc_data.model.evaluate')->delete($this->getUser()->getVccCode(), $ids);

        $code = isset($result['code']) ? $result['code'] : '';
        $message = isset($result['message']) ? $result['message'] : '';

        if ($code == 200) {
            return new JsonResponse(array('error'=>0, 'message'=>$this->trans('Delete Success')));
        } else {
            return new JsonResponse(array('error'=>1, 'message'=>$message));
        }
    }

    /**
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function detailAction()
    {
        $vccCode = $this->getUser()->getVccCode();
        $result = $this->get('icsoc_data.model.evaluate')->evaluateList(array('vcc_code'=>$vccCode));
        $data = isset($result['data']) ? $result['data'] : array();
        $evaluates = array();
        foreach ($data as $v) {
            $evaluates[$v['id']] = $v['name'];
        }

        /** @var  $queues (全部技能组数据) */
        $queues = $this->get('icsoc_data.model.queue')->getQueueNameKeyedByIdArray($this->getUser()->getVccId(), true);

        /** @var  $agents (全部坐席数据) */
        $agents = $this->get('icsoc_data.model.agent')->getAgentNameKeyedByIdArray($this->getUser()->getVccId(), true);

        $options = array(
            'evaluate_result'=>array('text'=>'Evaluate Result', 'type'=>2, 'options'=>$this->container->getParameter('EVALUATES'), 'all'=>''),
            'call_id'=>array('text'=>'Call ID', 'type'=>1),
            'agent_id'=>array('text'=>'Agent', 'type'=>2, 'options'=>$agents),
            'que_id'=>array('text'=>'Queues', 'type'=>2, 'options'=>$queues),
        );

        return $this->render(
            'IcsocEvaluateBundle:Default:detail.html.twig',
            array(
                'evaluates'=>$evaluates,
                'options'=>$options,
                'date' =>$this->getData(),
            )
        );
    }

    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function detailListAction(Request $request)
    {
        $page = $request->get('page', 1);
        $rows = $request->get('rows', 10);
        $sord = $request->get('sord', 'asc');
        $sidx = $request->get('sidx', 'id');
        $param = $request->get('param', '');

        $param = html_entity_decode(urldecode($param));

        $info = array(
            'pagination'=>array('rows'=>$rows, 'page'=>$page),
            'sort'=>array('order'=>$sord, 'field'=>$sidx),
            'filter'=> !empty($param) ? json_decode($param, true) : array(),
        );

        $vccCode = $this->getUser()->getVccCode();
        $list = $this->get('icsoc_data.model.evaluate')
            ->evaluateDetailList(array('vcc_code'=>$vccCode, 'info'=>json_encode($info)));

        $data['rows'] = (isset($list['data']) && !empty($list['data'])) ? $list['data'] : array();
        $data['page'] = $page;
        $data['total'] = isset($list['totalPage']) ? $list['totalPage'] : 0;
        $data['records'] = isset($list['total']) ? $list['total'] : 0;

        return new JsonResponse($data);
    }

    /**
     * The evaluate detail
     *满意度评价明细报表
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function recordListAction()
    {
        $em = $this->getDoctrine()->getManager();
        $vccId = $this->getUser()->getVccId();
        $queues = $this->container->get('icsoc_data.model.queue')->getQueueNameKeyedByIdArray($vccId, true);
        $isEnableGroup = $this->getDoctrine()->getRepository("IcsocSecurityBundle:CcCcodConfigs")->isEnableGroup($vccId);
        $isSpecial = $this->container->get("icsoc_core.common.class")->getIsAdmin();
        /** @var  array $groups 所有业务组 */
        $groups = $em->getRepository("IcsocSecurityBundle:WinGroup")->getGroupsName($vccId);
        $evaluates = $this->container->get('icsoc_data.model.evaluate')
            ->getEvaluateConfig(
                array(
                    'vccId'=> $vccId
                )
            );
        $evaluates = json_decode($evaluates, true);
        $isOrigin = $this->container->get('icsoc_data.model.evaluate')->getEvaluateVerByVccId($vccId);

        $options = array(
            'ag_num'=>array('text'=>'Agent', 'type'=>2),
            'call_type'=>array('text'=>'Call type', 'type'=>2, 'options'=>$this->callType),
            'cus_phone'=>array('text'=>'Cus Phone', 'type'=>1),
            'ag_phone'=>array('text'=>'Agent Phone', 'type'=>1),
            'que_id'=>array('text'=>'Queues', 'type'=>2, 'options'=>$queues),
            'ssecs'=>array('text'=>'When the length of more than', 'type'=>1),
            'esecs'=>array('text'=>'When the length of less than', 'type'=>1),
            'evaluates'=> array('text'=>'Evaluate Result Select', 'type'=>3, 'options'=> $evaluates),
            'serv_num' => array('text' => 'Server Num', 'type' => 1),
        );
        if ($isOrigin == 1) {
            $options['evaluates'] = array('text' => 'Evaluate Result', 'type' => 2, 'options' => $this->evaluates, 'all' => '-5');
        }
        if ($isEnableGroup) {
            $options['group_id'] = array('text'=>'Business Group', 'type'=>2, 'options'=>$groups);
        }
        $actionList = $this->getActionList();
        $actions = explode(',', $actionList);
        $isBatchDown = ($actionList == 'all'  || in_array('icsoc_recording_list_batch_down_data', $actions))
            ? true : false;

        $result = $this->container->get('icsoc_data.model.evaluate')->getEvaluateInfo($this->getUser()->getVccCode());
        $data = isset($result['data']) ? $result['data'] : array();

        return $this->render("IcsocEvaluateBundle:Default:indexDetail.html.twig", array(
            'date' => $this->getData(),
            'options'=>$options,
            'isBatchDown'=>$isBatchDown,
            'isEnableGroup' => $isEnableGroup,
            'evaluateConfig' => $evaluates,
            'evaluates' => $data,
            'isOrigin' => $isOrigin,
            'isSpecial' => $isSpecial
        ));
    }

    /**
     * The evaluate detail data
     *满意度评价明细报表数据
     * @param Request $request
     * @return JsonResponse
     */
    public function recordListDataAction(Request $request)
    {
        $data = $request->get('param', '');
        $data = html_entity_decode(urldecode($data));
        $page = $request->get('page', 1);
        $rows = $request->get('rows', 10);
        $sord = $request->get('sord', 'desc');
        $sidx = 'start_time';
        $export = $request->get('export', '');

        $info = array(
            'export' => $export,
            'pagination' => array('rows'=>$rows, 'page'=>$page),
            'filter' => !empty($data) ? json_decode($data, true) : array(),
            'sort' => array('order'=>$sord, 'field'=>$sidx),
        );
        /*$list = $this->get('icsoc_data.model.evaluate')->recordList(
            array(
                'vcc_code'=>$this->getUser()->getVccCode(),
                'info'=>json_encode($info),
                'forPageParam' => json_decode($forPageParam, true),
            )
        );*/

        if ($info['filter']['isOrigin'] == 1) {
            $list = $this->get('icsoc_data.model.evaluate')->recordListFromElasticsearchForOldEvaluateConfig(
                array(
                    'vcc_code'=>$this->getUser()->getVccCode(),
                    'info'=>json_encode($info),
                )
            );
        } else {
            $list = $this->get('icsoc_data.model.evaluate')->recordListFromElasticsearch(
                array(
                    'vcc_code'=>$this->getUser()->getVccCode(),
                    'info'=>json_encode($info),
                )
            );
        }

        $em = $this->getDoctrine()->getManager();
        $vccId = $this->getVccId();
        $isEnableGroup = $this->getDoctrine()->getRepository("IcsocSecurityBundle:CcCcodConfigs")->isEnableGroup($vccId);
        /** @var  array $groups 所有业务组 */
        $groups = $em->getRepository("IcsocSecurityBundle:WinGroup")->getGroupsName($vccId);
        if (isset($list['code']) && $list['code'] == 200) {
            foreach ($list['data'] as $k => $v) {
                $list['data'][$k]['group_id'] = isset($groups[$v['group_id']]) ? $groups[$v['group_id']] : '';
            }
        }

        /** 导出功能 */
        if (!empty($export)) {
            $evaluates = $this->container->get('icsoc_data.model.evaluate')
                ->getEvaluateConfig(
                    array(
                        'vccId'=> $vccId
                    )
                );
            $res = array();
            $evaluates = json_decode($evaluates, true);
            if (!empty($evaluates)) {
                $index = 1;
                foreach ($evaluates as $key => $val) {
                    foreach ($val['keys'] as $k => $v) {
                        $res[$val['id']] = 'Evaluate Result'.$index;
                    }
                    $index += 1;
                }
            }

            /** @var  $title (导出字段) */
            $title = array(
                'ag_num' => array(
                    'title' => 'Agent Num',
                    'type' => Col::TYPE_STRING,
                ),
                'ag_name' => array(
                    'title' => 'Agent Name',
                    'type' => Col::TYPE_STRING,
                ),
                'que_name' => array(
                    'title' => 'Queue',
                    'type' => Col::TYPE_STRING,
                ),
                'call_type' => array(
                    'title' => 'Call type',
                    'type' => Col::TYPE_STRING,
                ),
                'server_num' => array(
                    'title' => 'Relay number',
                    'type' => Col::TYPE_STRING,
                ),
                'ag_phone' => array(
                    'title' => 'Agent Phone',
                    'type' => Col::TYPE_STRING,
                ),
                'cus_phone' => array(
                    'title' => 'The customer number',
                    'type' => Col::TYPE_STRING,
                ),
                'start_time' => array(
                    'title' => 'Start Time',
                    'type' => Col::TYPE_STRING,
                    'filters' => array(
                        array(
                            'filter' => 'datetime',
                            'format' => 'Y-m-d H:i:s',
                        )
                    ),
                ),
                'end_time' => array(
                    'title' => 'End time',
                    'type' => Col::TYPE_STRING,
                    'filters' => array(
                        array(
                            'filter' => 'datetime',
                            'format' => 'Y-m-d H:i:s',
                        )
                    ),
                ),
                'conn_secs' => array(
                    'title' => 'The long recording time',
                    'type' => Col::TYPE_NUMBER,
                ),
            );
            if (!empty($res)) {
                foreach ($res as $id => $evaluate) {
                    $title[$id] = array(
                        'title' => $evaluate,
                        'type' => Col::TYPE_STRING
                    );
                }
            }

            if ($isEnableGroup) {
                $title = array(
                    'ag_num' => array(
                        'title' => 'Agent Num',
                        'type' => Col::TYPE_STRING,
                    ),
                    'ag_name' => array(
                        'title' => 'Agent Name',
                        'type' => Col::TYPE_STRING,
                    ),
                    'group_id' => array(
                        'title' => 'Business Group',
                        'type' => Col::TYPE_STRING,
                    ),
                    'que_name' => array(
                        'title' => 'Queue',
                        'type' => Col::TYPE_STRING,
                    ),
                    'call_type' => array(
                        'title' => 'Call type',
                        'type' => Col::TYPE_STRING,
                    ),
                    'server_num' => array(
                        'title' => 'Relay number',
                        'type' => Col::TYPE_STRING,
                    ),
                    'ag_phone' => array(
                        'title' => 'Agent Phone',
                        'type' => Col::TYPE_STRING,
                    ),
                    'cus_phone' => array(
                        'title' => 'The customer number',
                        'type' => Col::TYPE_STRING,
                    ),
                    'start_time' => array(
                        'title' => 'Start Time',
                        'type' => Col::TYPE_STRING,
                        'filters' => array(
                            array(
                                'filter' => 'datetime',
                                'format' => 'Y-m-d H:i:s',
                            )
                        ),
                    ),
                    'end_time' => array(
                        'title' => 'End time',
                        'type' => Col::TYPE_STRING,
                        'filters' => array(
                            array(
                                'filter' => 'datetime',
                                'format' => 'Y-m-d H:i:s',
                            )
                        ),
                    ),
                    'conn_secs' => array(
                        'title' => 'The long recording time',
                        'type' => Col::TYPE_NUMBER,
                    ),
                );
            }

            if ($info['filter']['isOrigin'] == 1) {//值为1时，是老的满意度配置情况
                $title['evaluate'] = array(
                    'title' => 'Evaluate Result',
                    'type' => Col::TYPE_STRING,
                );

                /** @var array $evaluates 满意度信息 */
                $evaluatesArr = $this->container->get('icsoc_data.model.evaluate')->getEvaluateInfo($this->getUser()->getVccCode());
                $evaluatesArr = isset($evaluatesArr['data']) ? $evaluatesArr['data'] : array();
                if (!empty($evaluatesArr)) {
                    foreach ($evaluatesArr as  $evaluate) {
                        $title['evaluate_'.$evaluate['id']] = array(
                            'title' => $evaluate['name'],
                            'type' => Col::TYPE_STRING,
                        );
                    }
                }
            } else {
                if (!empty($res)) {
                    foreach ($res as $id => $evaluate) {
                        $title[$id] = array(
                            'title' => $evaluate,
                            'type' => Col::TYPE_STRING
                        );
                    }
                }
            }

            $list = (isset($list['data']) && !empty($list['data'])) ? $list['data'] : array();
            switch ($export) {
                case 'csv':
                    return $this->container->get('icsoc_data.model.batchExport')->exportCsv($title, $list);
                case 'excel':
                    return $this->container->get('icsoc_data.model.batchExport')->exportExcel($title, $list);
                default:
                    exit;
            }
        }

        $result = array(
            'records' => isset($list['total']) ? $list['total'] : 0,
            'rows' => (isset($list['data']) && !empty($list['data'])) ? $list['data'] : array(),
            'total' => isset($list['totalPage']) ? $list['totalPage'] : 0,
            'page' => isset($list['page']) ? $list['page'] : $page,
        );

        return new JsonResponse($result);
    }

    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function setConfigAction(Request $request)
    {
        $config = $request->get('evaluateConfig', '');
        if (empty($config)) {
            return new JsonResponse(array('err'=>true, 'msg'=>'数据不全'));
        }
        json_decode($config, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            return new JsonResponse(array('err'=>true, 'msg'=>'数据格式有正确'));
        }

        $eid = $this->get("doctrine.dbal.default_connection")->fetchColumn(
            "SELECT id FROM cc_evaluates_config WHERE vcc_id = ? LIMIT 1",
            array($this->getVccId())
        );
        if ($eid) {
            $this->get('doctrine.dbal.default_connection')
                ->update('cc_evaluates_config', array('evaluate_config'=>$config,'update_time'=>time()), array('id'=>$eid));
        } else {
            $data['evaluate_config'] = $config;
            $data['vcc_id'] = $this->getVccId();
            $data['update_time'] = time();
            $this->get('doctrine.dbal.default_connection')->insert('cc_evaluates_config', $data);
        }

        return new JsonResponse(array('err'=>false));
    }
}
